/*
 * Copyright 2008 Johnny Jian
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.getris.game.score

import groovy.xml.MarkupBuilder

class HighScoreManager {

	def top
	def list

	HighScoreManager() {
		list = new TreeSet({ a, b ->
			a.score == b.score ? a.name.compareTo(b.name) : a.score < b.score ? 1 : -1
		} as Comparator)
	}

	def reset() {
		list.clear()
	}

	def saveTo(file) {
		def writer = new BufferedWriter(new PrintWriter(file))
		def xml = new MarkupBuilder(writer)
		xml.highscores {
			list.each { i ->
				item {
					name(i.name)
					score(i.score)
				}
			}
		}
	}

	def loadFrom(file) {
		reset()
		if (file.exists()) {
			def highscores = new XmlSlurper().parse(file)
			highscores.item.each { item ->
				this << [item.name.text(), item.score.toInteger()]
			}
		}
	}

	def isTopScore(score) {
		score > 0 && (list.size() < top || score > list.last().score)
	}

	def addScore(item) {
		item = item as ScoreItem
		if (isTopScore(item.score)) {
			while (list.size() >= top) {
				list.remove(list.last())
			}
			list << item
		}
	}

	def leftShift = this.&addScore

	def iterator() {
		list.iterator()
	}

}

class ScoreItem {

	def name
	def score

	ScoreItem() {}

	ScoreItem(name, score) {
		this.name = name
		this.score = score
	}

}
